from typing import List


class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []

        res = []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            # 从左到右遍历上边
            for i in range(left, right + 1):
                res.append(matrix[top][i])

            # 第一层已经加了进去
            top += 1
            if top > bottom:
                break

            # 从上到下遍历右边
            for i in range(top, bottom + 1):
                res.append(matrix[i][right])
            right -= 1
            if left > right:
                break

            # 从右到左遍历下边
            for i in range(right, left - 1, -1):
                res.append(matrix[bottom][i])
            bottom -= 1
            if top > bottom:
                break

            # 从下到上遍历左边
            for i in range(bottom, top - 1, -1):
                res.append(matrix[i][left])
            left += 1

        return res


matrix = [[1,2,3],[4,5,6],[7,8,9]]
a = Solution().spiralOrder(matrix)